<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, computed } from 'vue';
import { listFoodByBussinessId, addFood, decreaseFood, getBusinessById, getCartByBusinessId } from '@/api';
import { nextTick } from 'vue'
import { showToast } from 'vant';
const router = new useRouter();
const route = useRoute()
const onClickLeft = () => router.push('/');
const show = ref(false)
const foodslist = ref([])
const businessid = route.params.id
const businessinfo = ref({})
const cartItems = ref([]);
const initData = async () => {
    try {
        const response = await listFoodByBussinessId(businessid);
        foodslist.value = response.data.records;
    } catch (error) {
        console.error('获取商家列表数据时出错:', error);
    }
};
initData()

const initBusinessInfo = async () => {
    try {
        const response = await getBusinessById(businessid);
        businessinfo.value = response.data;
        console.log(businessinfo.value)
    } catch (error) {
        console.error('获取商家信息时出错:', error);
    }
};
initBusinessInfo()

const getCart = async () => {
    try {
        const response = await getCartByBusinessId(businessid);
        cartItems.value = response.data.records;
        console.log(cartItems.value)
        // 更新foodslist中的quantity
        cartItems.value.forEach(cartItem => {
            const matchedFood = foodslist.value.find(food => food.foodId === cartItem.foodId);
            if (matchedFood) {
                matchedFood.quantity = cartItem.quantity;
                matchedFood.isSelected = true; // 如果在购物车中，标记为已选择
            }
        }
        );
    } catch (error) {
        console.error('获取购物车时出错:', error);
    }
};
getCart()

const popupContent = computed(() => {
    return cartItems.value.map(item => ({
        name: item.foodName,
        price: item.foodPrice.toFixed(2),
        quantity: item.quantity,
        id: item.foodId,
        img: item.foodImg
    }));
});
foodslist.value.forEach(food => {
    food.showStepper = ref(false);
    food.quantity = ref(1); // 初始值为1

});
const updateFoodQuantity = async (food, isAdding) => {
    console.log(food.quantity)
    try {
        const currentQuantity = food.quantity;
        if (isAdding) {
            // 增加操作
            await addFood(businessid, food.foodId);
        } else {
            // 减少操作
            if (currentQuantity > 1) {
                await decreaseFood(businessid, food.foodId);
            } else if (currentQuantity === 1) {
                await decreaseFood(businessid, food.foodId);
                food.isSelected = false;
                food.showStepper = false;
            }
        }
        getCart();
    } catch (error) {
        console.error(isAdding ? '增加商品数量时出错' : '减少商品数量时出错', error);
    }
    // 确保主页面状态同步更新
    const mainItem = foodslist.value.find(item => item.foodId === food.foodId);
    if (mainItem) {
        mainItem.isSelected = food.isSelected;
        mainItem.showStepper = food.showStepper;
        mainItem.quantity = food.quantity;
    }
};
const handleAddToCart = (food) => {
    if (!food.isSelected) {
        food.quantity = 1; // 仅在首次添加到购物车时设置为1
    }
    food.isSelected = true;
    updateFoodQuantity(food, true);
};
const totalPrice = computed(() => {
    let accumulatedTotal = foodslist.value.reduce((total, food) => {
        if (food && food.isSelected && food.quantity) {
            return total + (food.quantity * food.foodPrice);
        }
        return total;
    }, 0);
    // 在累加完成后，对总和进行格式化处理
    return Number(accumulatedTotal.toFixed(2));

});
const shouwCart = () => {
    show.value = true;
    getCart()
}
const onCartItemQuantityChange = async (index, newQuantity) => {
    try {
        const currentItem = cartItems.value[index];
        if (newQuantity <= 0) {
            const { foodId } = currentItem;
            await decreaseFood(businessid, foodId);
            // 创建一个新的数组，跳过当前被删除的元素
            const updatedCartItems = [
                ...cartItems.value.slice(0, index),
                ...cartItems.value.slice(index + 1)
            ];
            // 直接赋值给响应式引用
            cartItems.value = updatedCartItems;
            // 更新主界面状态（确保在更新cartItems之后）
            const mainItem = foodslist.value.find(food => food.foodId === foodId);
            if (mainItem) {
                mainItem.showStepper = false;
                mainItem.isSelected = false;
                mainItem.quantity = 0;
            }
            // 使用nextTick确保DOM更新
             await nextTick();
        } else {
            if (newQuantity > currentItem.quantity) {
                await addFood(businessid, currentItem.foodId);
            } else if (newQuantity < currentItem.quantity) {
                await decreaseFood(businessid, currentItem.foodId);
            }
            currentItem.quantity = newQuantity;
        }

        // 同步主界面的商品状态
        const mainItemToUpdate = foodslist.value.find(food => food.foodId === currentItem.foodId);
        if (mainItemToUpdate) {
            // 确保只有在商品未被删除（即数量仍大于0）时才更新主界面的quantity
            if (newQuantity > 0) {
                mainItemToUpdate.quantity = newQuantity;
            }
            mainItemToUpdate.showStepper = newQuantity > 0;
            mainItemToUpdate.isSelected = newQuantity > 0;
        }
    } catch (error) {
        console.error('操作商品数量时出错:', error);
    }
};
const onClickButton = async () => {
    if (totalPrice.value > businessinfo.value.starPrice) {
        router.push({ path: '/confirmorder', query: { businessid: businessid } })
    }
    else {
        showToast('未达到起送价')
    }
}

const totalQuantity = computed(() => {
    let total = 0;
    for (let i = 0; i < cartItems.value.length; i++) {
        total += cartItems.value[i].quantity;
    }
    return total;
})
</script>
<template>
    <div class="">
        <div class="sticky-container"> <van-nav-bar title="点餐" left-text="返回" left-arrow @click-left="onClickLeft" />
            <div class="business-info">
                <span style="margin-left: 15px;">
                    <img :src="businessinfo.businessImg" alt="" style="width: 100px;height: 90px;border-radius: 5px;margin-bottom: 15px;">
                    <div style="display: block; font-size: 10px">
                        <div style="color: #1989fa;font-size: 18px;font-weight: 600;">{{ businessinfo.businessName }}
                        </div>
                        <div style="display: flex;margin-top: 10px;">
                            <div>起送:{{ businessinfo.starPrice }}</div>
                            <div style="margin-left: 10px;">配送费:{{ businessinfo.deliveryPrice }}</div>
                        </div>
                    </div>
                </span>
            </div>
        </div>
        <div class="order-dishes" :style="{ height: '100%', position: 'relative' }">
            <div class="content-area" :style="{ height: '100%', overflowY: 'auto' }">
                <van-card v-for="food in foodslist" :key="food.id" :price="food.foodPrice.toFixed(2)"
                    :desc="food.foodExplain" :thumb="food.foodImg" class="custom-card">
                    <template #footer>
                        <van-stepper v-if="food.isSelected" v-model="food.quantity" :min="0" :max="99" integer
                            theme="round" disable-input @plus="() => updateFoodQuantity(food, true)"
                            @minus="() => updateFoodQuantity(food, false)" />
                        <van-button style="margin-bottom: 0; width: 50px;height: 28px;" v-else
                            color="linear-gradient(to right, #ff6034, #ee0a24)" type="primary" size="small"
                            @click="() => handleAddToCart(food)">加购</van-button>
                    </template>
                    <template #title>
                        <label style="font-size: 18px;font-weight: 540;color: #1989fa;">{{ food.foodName }}</label>
                    </template>
                    <template #price>
                        <label style="font-size: 18px;">￥{{ food.foodPrice.toFixed(2) }}</label>
                    </template>
                </van-card>
            </div>
        </div>
        <van-action-bar>
            <div style="display: flex; flex-direction: column; margin: 10px; margin-bottom: 10px;">
                <div style="font-weight: bold; font-size: 14px;">总价:¥{{ totalPrice }}</div>
                <div style="margin-top: 10px; font-size: 11px;">配送费:¥{{ businessinfo.deliveryPrice }}</div>
            </div>


            <van-action-bar-button type="danger" color="rgb(120,137,250)" @click="shouwCart">
                <div style="display: flex; align-items: center;">
                    <van-badge :content="totalQuantity" position="top-left">
                        <template #default>
                            <van-icon size="25px" name="cart-o" />
                        </template>
                    </van-badge>
                    <label style="margin-left: 10px;">购物车</label>
                </div>
            </van-action-bar-button>
            <van-action-bar-button type="danger" text="结算" color="rgb(25,137,250)" @click="onClickButton" />
        </van-action-bar>
        <van-popup v-model:show="show" position="bottom" round :style="{ height: '50%' }">
            <!-- <div class="popup-content">
                <div v-for="(item, index) in popupContent" :key="item.id" class="item-span">
                    <van-image width="50" height="50" :src="item.img" />
                    <div class="item-col">{{ item.name }}</div>
                    <div class="item-col">单价: ¥{{ item.price }}</div>
                    <van-stepper v-model="item.quantity" :min="0" :max="99" integer theme="round"
                        @change="(quantity) => onCartItemQuantityChange(index, quantity)" />
                </div>
            </div> -->
            <van-cell-group inset>
                <van-cell v-for="(item,index) in popupContent" :key="item.id" :title="item.name" :label="item.price">

                    <template #icon>
                        <img :src="item.img" alt=""
                            style="width: 30px;height: 30px;border-radius:10px;margin-right: 20px; ">
                    </template>

                    <template #right-icon>
                        <van-stepper v-model="item.quantity" :min="0" :max="99" integer theme="round"
                        @change="(quantity) => onCartItemQuantityChange(index, quantity)" />
                    </template>
                </van-cell>
            </van-cell-group>

        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.sticky-container {
    position: sticky;
    top: 0;
    z-index: 1000;
    background-color: #fff;
    display: flex;
    flex-direction: column;
}

.business-info {
    position: sticky;
    top: 0;
    z-index: 1000;
    background-color: #fff;
    display: flex;
    align-items: center;
    gap: 10px;
}

.business-info span {
    display: flex;
    align-items: center;
    gap: 10px;
}

.order-dishes {
    display: flex;
    height: 100%;
    padding-bottom: 50px;
    overflow-y: auto;
}

.content-area {
    flex-grow: 1;
    overflow-y: auto;
}

.popup-content {
    box-sizing: border-box;
    padding-right: 50px;
}


.item-span {
    display: flex;
    width: 100%;
    margin: 20px;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #d4e2ef;
}


.item-col {
    // flex: 1 1 calc(33.3333% - 10px);
    // text-align: center;
    // min-height: 20px;
    // width: 10px;
    margin: 15px;
}

/* 修改标题字体大小 */
.van-card__title {
    font-size: 25px !important;
}

/* 修改描述字体大小 */
.van-card__desc {
    font-size: 25px !important;
}

/* 修改价格字体大小 */
.van-card__price {
    font-size: 15px !important;
}

/* 自定义card的类 */
.custom-card {
    /* 你也可以在这里添加其他自定义样式 */
    //   font-size: 25px !important;
}
</style>
